import { createRouter, createWebHashHistory, RouteRecordRaw } from 'vue-router'
import { nativeHandler } from 'qmp-native'
import { MetaRules } from '@/types/router-meta'

function h5Routes() {
  const allRoutes: any = []
  const routeFiles = require.context('./h5', true, /\.ts/)
  routeFiles.keys().forEach((key) => {
    const route = routeFiles(key).default
    allRoutes.push(...route)
  })
  return allRoutes
}

const routes: Array<RouteRecordRaw & MetaRules> = [
  ...h5Routes() //路由配置
]

const router = createRouter({
  // history: createWebHistory(), // history模式
  history: createWebHashHistory(), // hash模式
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { left: 0, top: 0 }
    }
  }
})

router.beforeEach(async (to, from, next): Promise<void> => {
  if (!to.meta.noTransition) {
    to.meta.transitionName = router.isBack ? 'page-back' : 'page-forward' // 设置页面前进、后退动画class
    router.isBack = false
  }
  // 原生app状态栏设置
  interface StatusBarParams {
    statusBarType: 1 | 2 // 设置原生app状态栏文字颜色： 1: 黑色  2：白色
    isToTop: boolean // 是否需要顶部距离(true:吸顶)
    statusBarBgColor: string // 设置原生app状态栏背景颜色
  }
  const toTextColor = to.meta.nativeAppStatusBarTextColor
  const fromTextColor = from.meta.nativeAppStatusBarTextColor
  const fromIsToTop = from.meta.nativeAppToTop === true ? true : false
  const isToTop = to.meta.nativeAppToTop === true ? true : false
  const statusBarHeight = localStorage.getItem('nativeAppStateBarHeight')
  const params: StatusBarParams = {
    statusBarType: to.meta.nativeAppStatusBarTextColor === 'white' ? 2 : 1,
    isToTop,
    statusBarBgColor: isToTop ? '' : `${to.meta.nativeAppStatusBarBgColor || '#F2F4F3'}` // 状态栏颜色
  }
  // console.log('状态栏更新参数', params)
  if (statusBarHeight) {
    // 已获取到原生app状态栏高度时
    to.meta.nativeAppStatusBarHeight = Number(statusBarHeight)
    // 跳转前后页面设置的原生app状态栏颜色，背景色，是否置顶不完全一致时，调用原生方法改变状态栏
    if (
      !(
        toTextColor === fromTextColor &&
        fromIsToTop === isToTop &&
        to.meta.nativeAppStatusBarBgColor === from.meta.nativeAppStatusBarBgColor
      )
    ) {
      nativeHandler('setupStatusBarStyle', params)
    }
    next()
    return
  }
  // 第一次进入应用，获取原生app高度并缓存高度，并且异步跳转页面
  try {
    const res = await nativeHandler('setupStatusBarStyle', params)
    to.meta.nativeAppStatusBarHeight = res.statusBarHeight // 记录原生app返回的状态栏高度
    res.statusBarHeight && localStorage.setItem('nativeAppStateBarHeight', res.statusBarHeight)
  } catch (error) {
    to.meta.nativeAppStatusBarHeight = 0
  }
  next()
})
export default router
